package com.lucher.mes.controller;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.lucher.mes.common.Tools;
import com.lucher.mes.dao.PrisonerMapper;
import com.lucher.mes.po.Prisoner;
import com.lucher.mes.po.Workorder;
import com.lucher.mes.service.ISystemparaService;

@Controller
@RequestMapping("/prisoner")  
public class PrisonerController extends BaseController{
	@Resource  
    private PrisonerMapper prisonerDao; 
	@Autowired
	private ISystemparaService systemparaService;
	/**
	 * 查询操作员信息
	 */
	@RequestMapping(value = "/findByList")
	public String findByList(Prisoner form) {
		return "prisoner/findPrisonerList";
	}
	
	/**
	 * 查询用户信息Json
	 */
	@ResponseBody
	@RequestMapping(value = "/findListJson")
	public Map<String, Object> findListJson(Prisoner form) {
		//封装JSon的Map
		Map<String, Object> result = new HashMap<String, Object>(); 
		List<HashMap<String, Object>> objectlist = new ArrayList<HashMap<String, Object>>();
		
		Integer total = prisonerDao.findByCount(form);
		List<Prisoner> list = prisonerDao.findPrisonerListForPage(form);
		
		for (Prisoner prisoner : list) {
			HashMap<String, Object> objectMap = new HashMap<String, Object>();
			
			objectMap.put("id", prisoner.getId());
			objectMap.put("prisonercode", prisoner.getPrisonercode());
			objectMap.put("prisonername", prisoner.getPrisonername());
			objectMap.put("password", prisoner.getPassword());
			objectMap.put("addtime",  StringUtils.isEmpty(prisoner.getAddtime())?"":Tools.getStr(prisoner.getAddtime()).substring(0, 19));
			objectMap.put("status",  prisoner.getStatus());
			objectMap.put("sex", prisoner.getSex());
			objectMap.put("birthday", StringUtils.isEmpty(prisoner.getBirthday())?"":Tools.getStr(prisoner.getBirthday()).substring(0, 10));
			objectMap.put("identification", prisoner.getIdentification());
			objectMap.put("email", prisoner.getEmail());
			objectMap.put("address", prisoner.getAddress());
			objectMap.put("phone", prisoner.getPhone());
			objectMap.put("level", prisoner.getLevel());
			objectMap.put("status", prisoner.getStatus());
			objectMap.put("department", prisoner.getDepartment());
			objectMap.put("crimename", prisoner.getCrimename());
			objectMap.put("nation", prisoner.getNation());
			objectMap.put("nativeplace", prisoner.getNativeplace());
			objectMap.put("age", prisoner.getAge());
			objectMap.put("prisonterm", prisoner.getPrisonterm());
			objectMap.put("leftprisonterm", prisoner.getLeftprisonterm());
			objectMap.put("majorcriminals", prisoner.getMajorcriminals());
			objectMap.put("prisonlevel", prisoner.getPrisonlevel());
			objectMap.put("prisontime", StringUtils.isEmpty(prisoner.getPrisontime())?"":Tools.getStr(prisoner.getPrisontime()).substring(0, 19));
			objectMap.put("headfilepath", prisoner.getHeadfilepath());
			objectMap.put("fingerfilepath", prisoner.getFingerfilepath());
			objectMap.put("remark", prisoner.getRemark());
			objectlist.add(objectMap);
		}
		
		result.put("code", "0");
		
		result.put("count", total);
		result.put("data", objectlist);
		return result;
	}

	/**
	 * 添加用户信息初始化
	 * 
	 * @return
	 */
	@RequestMapping(value = "/addInit")
	public String addInit(Prisoner form) {
		return "prisoner/addPrisoner";
	}

	/**
	 * 新增
	 */
	@ResponseBody //此标志就是返回jesion数据给页面的标志
	@RequestMapping(value = "/save")
	public Map<String,Object>  save(Prisoner form) {
		
		//封装返回给页面的json对象
		HashMap<String,Object> responseJson = new HashMap<String,Object>();
		responseJson.put("code", "0");
		
		if ("".equals(form.getPrisonercode())) {
			responseJson.put("flag", "0"); //添加失败
			responseJson.put("msg", "操作失败，犯人编号不能为空");
			return responseJson;
		} else {
			Prisoner oldPrisoner = prisonerDao.findPrisonerByPrisonercode(form);
			if (oldPrisoner != null) {
				responseJson.put("flag", "0");//添加失败
				responseJson.put("msg", "操作失败，犯人编号已经存在");
				return responseJson;
			}
		}
		
		form.setStatus("入狱");// 有效
		form.setAddtime(Tools.getCurrentTime());// 取当前时间
		prisonerDao.insertSelective(form);
		
		responseJson.put("flag", "1");//删除成功
		responseJson.put("msg", "操作成功");
		
		return responseJson;
	}

	/**
	 * 更新初始化
	 */
	@RequestMapping(value = "/updateInit")
	public String updateInit(Prisoner form) {
		Prisoner prisoner = prisonerDao.selectByPrimaryKey(form.getId());
		prisoner.setPrisoner(prisoner);
		form.setPrisoner(prisoner);
		return "prisoner/updatePrisoner";
	}

	/**
	 * 更新
	 */
	@ResponseBody //此标志就是返回jesion数据给页面的标志
	@RequestMapping(value = "/update")
	public Map<String,Object> update(Prisoner form) {
		//封装返回给页面的json对象
		HashMap<String,Object> responseJson = new HashMap<String,Object>();
		responseJson.put("code", "0");
		
		if ("".equals(form.getPrisonercode())) {
			responseJson.put("flag", "0"); //添加失败
			responseJson.put("msg", "操作失败，犯人编号不能为空");
			return responseJson;
		} 
		
		Prisoner oldPrisoner = prisonerDao.findPrisonerByPrisonercode(form);
		if (oldPrisoner != null && !oldPrisoner.getId().equals(form.getId())) {
			responseJson.put("flag", "0"); //添加失败
			responseJson.put("msg", "操作失败，犯人编号已经存在");
			return responseJson;
		}
		
		// 修改信息
		Prisoner prisoner = prisonerDao.selectByPrimaryKey(form.getId());
		form.setFingerfilepath(prisoner.getFingerfilepath());
		form.setHeadfilepath(prisoner.getHeadfilepath());
		prisonerDao.updateByPrimaryKeySelective(form);
		responseJson.put("flag", "1");//删除成功
		responseJson.put("msg", "操作成功");
		return responseJson;
	}
    
	/**
	 * 删除操作员
	 * @return
	 */
	@ResponseBody //此标志就是返回jesion数据给页面的标志
	@RequestMapping(value="/delete")
	public Map<String,Object> delete(Prisoner form) {
		//封装返回给页面的json对象
		HashMap<String,Object> responseJson = new HashMap<String,Object>();
		responseJson.put("code", "0");
		prisonerDao.deleteByPrimaryKey(form.getId());

		responseJson.put("flag", "1");//删除成功
		responseJson.put("msg", "删除成功");
		
		return responseJson;
	}
	
	/**
	 * 删除操作员
	 * @return
	 */
	@ResponseBody //此标志就是返回jesion数据给页面的标志
	@RequestMapping(value="/deleteBatch")
	public Map<String,Object> deleteBatch(@RequestBody List<Prisoner> formlist) {
		//封装返回给页面的json对象
		HashMap<String,Object> responseJson = new HashMap<String,Object>();
		responseJson.put("code", "0");
		for (Prisoner prisoner : formlist) {
			prisonerDao.deleteByPrimaryKey(prisoner.getId());
		}

		responseJson.put("flag", "1");//删除成功
		responseJson.put("msg", "删除成功");
		
		return responseJson;
	}
	
	/**
     * 上传头像图片
     * @param session
     * @param file
     * @param ui
     * @return
     * @throws IOException 
     * @throws IllegalStateException 
     */
    @RequestMapping(value="saveHeadfilepath")
    @ResponseBody //此标志就是返回jesion数据给页面的标志
    public  Map<String,Object> saveHeadfilepath(@RequestParam("file") MultipartFile file,@ModelAttribute Prisoner prisoner,HttpServletRequest request) throws IllegalStateException, IOException{
        String oldName = file.getOriginalFilename();
        //String path = request.getServletContext().getRealPath("/upload/");
        String upload_file_path = systemparaService.findSystemParaByCodeStr("upload_file_path");
        String folderpath = upload_file_path + File.separatorChar + "prisoner" + File.separatorChar + "head";
		 File folder = new File(folderpath);
		 if (!folder.exists()) {
			folder.mkdirs();
		 }
        String fileName = changeName(oldName);
        fileName = folderpath + File.separatorChar + fileName;
        File file1 = new File(fileName);
        file.transferTo(file1);
        
        //System.out.println(ui.getId());
        prisoner.setHeadfilepath(fileName);
        prisonerDao.updateByPrimaryKeySelective(prisoner);
        
        
        //封装返回给页面的json对象
		HashMap<String,Object> responseJson = new HashMap<String,Object>();
		responseJson.put("code", "0");
		responseJson.put("msg", "");
		HashMap<String,Object> data = new HashMap<String,Object>(); 
		data.put("src", fileName);
		responseJson.put("data", data);
       //String str = "{\"code\": 0,\"msg\": \"\",\"data\": {\"src\":\"" + fileName + "\"}}";
        
        return responseJson;
    }
    
    /**
     * 上传指纹图片
     * @param session
     * @param file
     * @param ui
     * @return
     * @throws IOException 
     * @throws IllegalStateException 
     */
    @RequestMapping(value="saveFingerfilepath")
    @ResponseBody //此标志就是返回jesion数据给页面的标志
    public  Map<String,Object> saveFingerfilepath(@RequestParam("file") MultipartFile file,@ModelAttribute Prisoner prisoner,HttpServletRequest request) throws IllegalStateException, IOException{
        String oldName = file.getOriginalFilename();
        //String path = request.getServletContext().getRealPath("/upload/");
        String upload_file_path = systemparaService.findSystemParaByCodeStr("upload_file_path");
        String folderpath = upload_file_path + File.separatorChar + "prisoner" + File.separatorChar + "finger";
		 File folder = new File(folderpath);
		 if (!folder.exists()) {
			folder.mkdirs();
		 }
        String fileName = changeName(oldName);
        fileName = folderpath + File.separatorChar + fileName;
        File file1 = new File(fileName);
        file.transferTo(file1);
        
        //System.out.println(ui.getId());
        prisoner.setFingerfilepath(fileName);
        prisonerDao.updateByPrimaryKeySelective(prisoner);
        
        
        //封装返回给页面的json对象
		HashMap<String,Object> responseJson = new HashMap<String,Object>();
		responseJson.put("code", "0");
		responseJson.put("msg", "");
		HashMap<String,Object> data = new HashMap<String,Object>(); 
		data.put("src", fileName);
		responseJson.put("data", data);
       //String str = "{\"code\": 0,\"msg\": \"\",\"data\": {\"src\":\"" + fileName + "\"}}";
        
        return responseJson;
    }
    
    public static String changeName(String oldName){
        Random r = new Random();
        Date d = new Date();
        String newName = oldName.substring(oldName.indexOf('.'));
        newName = r.nextInt(99999999) + d.getTime() + newName;
        return newName;
    }
    
    /**
	 * 图片下载
	 */
	@RequestMapping(value = "/getImgOrFileDownload")
	public Map<String, Object> getImgOrFileDownload(String filepath,HttpServletResponse response){
		
		if(StringUtils.isEmpty(filepath) || filepath.equals("null")){
			return null;
		}
		
		//门锁图片
        try {
			File excelTemplate = new File(filepath);
			response.reset();
			
			//图片文件，直接在页面显示图片
			if (Tools.isImage(excelTemplate)) {
				response.setHeader("Accept-Ranges", "bytes");  
	            response.setHeader("Pragma", "no-cache");  
	            response.setHeader("Cache-Control", "no-cache");  
	            response.setDateHeader("Expires", 0);  
			}else{//非图片文件，先下载
				response.setContentType("application/octet-stream");
				response.addHeader("Content-Length", "" + excelTemplate.length()); // 文件大小
				response.addHeader("Content-Disposition", "attachment;filename=" + Tools.getNowRandomTwo()+"."+Tools.getFilename(filepath));
			}
			
			System.out.println(Tools.getFilename(filepath));
			
			FileInputStream fis = new FileInputStream(excelTemplate);
			OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
			byte[] buffer = new byte[1024 * 1024];
			while (fis.read(buffer) > 0) {
				toClient.write(buffer);
			}
			fis.close();
			toClient.flush();
			toClient.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return null;
    }
}
